// components/lottie-view/lottie-view.js
import resource from '../../libs/resource.js'
import lottie from 'lottie-miniprogram';

Component({
  properties: {
    lottie_path: {
      type: String,
      value: resource.aboutme_lottie_popular_json,
    },
    math_width: {
      type: Boolean,
      value: false
    }
  },
  data: {
    hasNode: false
  },
  lifetimes: {
    attached: function () {

    },
    detached: function () {

    },
    ready: function () {
      // console.log('ready');
      let canvasId = (new Date()).valueOf()
      this.setData({
        canvasId
      })
    }
  },
  pageLifetimes: {
    show: function () {
      this.playLottie()
    },
    hide: function () {
      
    },
    resize: function () {
      
    }
  },
  methods: {
    getLottieFile() {
      wx.cloud.callFunction({
        name: 'video-json',
        data: {
          action: 'getLottieData',
          lottieName: this.data.lottie_path
        }
      }).then(res => {
        this.queryNode(res.result)
        // console.log("getLottieFile", res)
      }).catch(err => {
        // console.error("getLottieFile", err)
      })
    },
    queryNode(lottieObj) {
      var _this = this
      var canvasId = this.data.canvasId
      console.log("queryNode", `#${canvasId}`)
      const query = wx.createSelectorQuery().in(_this)
      query.select(`#lottie-${canvasId}`).node(res => {
        // console.log('createSelectorQuery', res)
        const canvas = res.node
        // console.log("canvas", canvas)
        const context = canvas.getContext('2d')
        lottie.setup(canvas)
        // console.log('createSelectorQuery', lottie)
        this.ani = lottie.loadAnimation({
          loop: true,
          autoplay: true,
          animationData: lottieObj,
          rendererSettings: {
            context
          }
        })
        _this.setData({
          hasNode: true
        })
      }).exec()
    },
    playLottie() {
      if (this.data.hasNode && this.ani) {
        this.ani.play()
      } else {
        this.getLottieFile()
      }
    }
  }
})